<template>
  <d2-container class="page">
    <div class="pd-y-10 full">
      <div class="flex pd-l-10" style="height:100%">
        <div class="mg-r-10 flex-item-1">
          <el-form :model="queryForm" :rules="rules" label-width="auto" size="mini" ref="queryForm">
            <el-form-item label="host" prop="host">
              <el-input style="width: 180px" v-model="queryForm.host" placeholder="请输入host" />
            </el-form-item>
            <el-form-item label="port" prop="port">
              <el-input style="width: 180px" v-model="queryForm.port" placeholder="请输入port" />
            </el-form-item>
            <el-form-item label="user" prop="user">
              <el-input style="width: 180px" v-model="queryForm.user" placeholder="请输入user" />
            </el-form-item>
            <el-form-item label="password" prop="password">
              <el-input show-password style="width: 180px" type="password" v-model="queryForm.password" placeholder="请输入password" />
            </el-form-item>
            <el-form-item label="database" prop="database">
              <el-input style="width: 180px" v-model="queryForm.database" placeholder="请输入database" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button class="sys-primary-btn w-180" type="primary" icon="el-icon-connection" @click="queryList">连接</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div style="height: calc(100% - 10px);width: calc(100% - 272px)">
          <sc-table-container>
            <d2-crud
              size="mini"
              ref="d2Crud"
              :columns="columns"
              :data="data"
              :options="d2crudOptions"
              :loading="loading"
              selection-row
              @selection-change="handleSelectionChange"
              :rowHandle="rowHandle"
              @detail="getDetailByName"
            >
              <div slot="header" class="pd-b-10">
                <span class="fs-12 pd-r-10">表名</span>
                <el-input style="width:180px;margin-right:10px" v-model="searchVal" placeholder="请输入表名称搜索" size="mini" />
                <span class="fs-12 pd-r-10">表名前缀</span>
                <el-input class="mg-r-10" size="mini" style="width: 220px" v-model="tablePrefix" placeholder="如：t_, t_basic_, t_app_" />
                <el-button size="mini" icon="el-icon-refresh" @click.native="reset">重置</el-button>
                <el-button class="sys-primary-btn" type="primary" size="mini" icon="el-icon-printer" @click="generate">一键生成下载</el-button>
              </div>
            </d2-crud>
          </sc-table-container>
        </div>
      </div>
    </div>

    <!-- 数据库表详情 -->
    <el-dialog class="jz-model" :title="detailTableName" :visible.sync="dialogTableVisible" width="60%">
      <el-table :data="detailGridData" size="mini" height="55vh">
        <el-table-column v-for="(item, key) in detailTableColumns" :key="key" :property="item" :label="item"></el-table-column>
      </el-table>
    </el-dialog>
  </d2-container>
</template>

<script>
import { list, getByName, generate, download } from '@/api/sys/database.api'
import { cloneDeep } from 'lodash'
import dayjs from 'dayjs'

export default {
  watch: {
    searchVal(v) {
      this.search(v)
    }
  },
  data() {
    return {
      selection: [],
      loading: false,
      queryForm: {
        host: '',
        user: '',
        password: '',
        port: '',
        database: ''
      },
      rules: {
        host: [{ required: true, message: '请输入host', trigger: 'blur' }],
        port: [{ required: true, message: '请输入port', trigger: 'blur' }],
        user: [{ required: true, message: '请输入host', trigger: 'blur' }],
        password: [{ required: true, message: '请输入password', trigger: 'blur' }],
        database: [{ required: true, message: '请输入database', trigger: 'blur' }]
      },
      d2crudOptions: {
        size: 'mini',
        stripe: true,
        border: true,
        height: '100%'
      },
      data: [],
      copyData: [],
      columns: [
        {
          title: '表名',
          key: 'name'
        },
        {
          title: '备注',
          key: 'comment'
        },
        {
          title: '创建时间',
          key: 'createTime',
          formatter: function run(row, cloumn, calValue) {
            return calValue == null ? '' : dayjs(calValue).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      ],
      rowHandle: {
        custom: [
          {
            text: '详情',
            type: 'primary',
            size: 'mini',
            emit: 'detail',
            class: 'table-row-handle-primary-btn'
          }
        ]
      },
      searchVal: '',
      tablePrefix: '',
      // 表详情弹框
      dialogTableVisible: false,
      detailTableName: '',
      detailGridData: [],
      detailTableColumns: []
    }
  },
  created() {
    const q = localStorage.getItem('_queryForm')
    if (q) {
      this.queryForm = JSON.parse(q)
      this.$nextTick(() => {
        this.queryList()
      })
    }
  },
  methods: {
    // 获取数据库表列表
    async queryList() {
      try {
        this.$refs['queryForm'].validate(async valid => {
          if (valid) {
            // this.loading = true
            let res = await list(this.queryForm)
            this.loading = false
            this.data = []

            this.data = res.aaData
            this.copyData = cloneDeep(res.aaData)
            localStorage.setItem('_queryForm', JSON.stringify(this.queryForm))
          }
        })
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    },
    // 查看表格详情
    async getDetailByName({ row }) {
      let res = await getByName({ name: row.name })
      this.detailTableName = `${row.name} ${row.comment}`
      this.detailTableColumns = ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_KEY', 'COLUMN_DEFAULT', 'COLUMN_COMMENT']
      this.detailGridData = res.aaData
      this.dialogTableVisible = true
    },
    // 多选操作
    handleSelectionChange(selection) {
      this.selection = selection
    },
    search(v) {
      if (!v) {
        this.data = this.copyData
      } else {
        let a = this.copyData.filter(item => item.name.includes(v))
        this.data = a
      }
    },
    reset() {
      this.searchVal = ''
      this.tablePrefix = ''
    },
    // 一键生成
    async generate() {
      if (this.selection.length == 0) {
        return this.$message.error('至少选择一张表生成！')
      }
      let tables = this.selection.map(item => {
        return {
          tableName: item.name,
          tableComment: item.comment
        }
      })
      await generate({ tables: tables, tablePrefix: this.tablePrefix })
      this.downloadTemplate('/api/database/download')
    },
    downloadTemplate(url) {
      if (!url) {
        return
      }
      let a = document.createElement('a')
      a.setAttribute('href', url)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
}
</script>
